<!--天猫账单-->
<script setup lang="ts">
import {AxiosPromise} from "axios";

defineOptions({
	name: "TMallBill",
	inheritAttrs: false,
});

import {ElLoading, UploadFile} from "element-plus";
import {
	getSysTmBillPage,
	getSysTmBillForm,
	saveSysTmBill,
	deleteSysTmBill,
	importSysTmBill,
	exportSysTmBill
} from "@/api/tMallBill";
import {StoreForm} from "@/api/store/types";
import {listAll} from "@/api/store";
import lodash from "lodash-es";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const importRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const monthValue = ref('')
const storeList = ref<StoreForm[]>();
const storeGroup = ref<[]>([]);

const queryParams = reactive<any>({
	pageNum: 1,
	pageSize: 20,
});

const sysTmBillList = ref<[]>();

const dialog = reactive<DialogOption>({
	visible: false,
});
const importDialog = reactive<DialogOption>({
	title: "天猫结算单数据导入",
	visible: false,
});

const excelFile = ref<File>();
const excelFilelist = ref<File[]>([]);
const formData = reactive<any>({});
const importParams = reactive<any>({});
const monthList = ref<[]>([]);

const rules = reactive({
	storeId: [{ required: true, message: "请输入店铺ID", trigger: "blur" }],
	orderNo: [{ required: true, message: "请输入订单编号", trigger: "blur" }],
	mainOrderNo: [{ required: true, message: "请输入主订单编号", trigger: "blur" }],
	bcOrder: [{ required: true, message: "请输入补差订单", trigger: "blur" }],
	ttOrder: [{ required: true, message: "请输入淘特订单", trigger: "blur" }],
	payNo: [{ required: true, message: "请输入支付单号", trigger: "blur" }],
	orderStatus: [{ required: true, message: "请输入订单状态", trigger: "blur" }],
	orderType: [{ required: true, message: "请输入订单类型", trigger: "blur" }],
	cancelReason: [{ required: true, message: "请输入订单关闭原因", trigger: "blur" }],
	orderCreateTime: [{ required: true, message: "请输入订单创建时间", trigger: "blur" }],
	orderPayTime: [{ required: true, message: "请输入订单付款时间", trigger: "blur" }],
	sendTime: [{ required: true, message: "请输入发货时间", trigger: "blur" }],
	confirmSendTime: [{ required: true, message: "请输入确认收货时间", trigger: "blur" }],
	shouldSendTime: [{ required: true, message: "请输入应发货时间", trigger: "blur" }],
});

const importRules = reactive({
	storeCode: [{ required: true, message: "请选择店铺", trigger: "change" }],
});




/**
 * 查询
 */
function handleQuery() {
	loading.value = true;
	if (lodash.size(monthList.value) > 0){
		lodash.set(queryParams, 'startMonth', monthList.value[0])
		lodash.set(queryParams, 'endMonth', monthList.value[1])
	}
	getSysTmBillPage(queryParams)
		.then(({ data }) => {
			sysTmBillList.value = data.list;
			total.value = data.total;
		})
		.finally(() => {
			loading.value = false;
		});
}

/**
 * 重置查询
 */
function resetQuery() {
	queryFormRef.value.resetFields();
	queryParams.pageNum = 1;
	handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(id?: number) {
	dialog.visible = true;
	if (id) {
		dialog.title = "修改天猫账单";
		getSysTmBillForm(id).then(({ data }) => {
			Object.assign(formData, data);
		});
	} else {
		dialog.title = "新增天猫账单";
	}
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
	dataFormRef.value.validate((isValid: boolean) => {
		if (isValid) {
			loading.value = false;
			saveSysTmBill(formData)
				.then(() => {
					ElMessage.success("保存成功");
					closeDialog();
					handleQuery();
				})
				.finally(() => (loading.value = false));
		}
	});
}

/**
 * 关闭弹窗
 */
function closeDialog() {
	dialog.visible = false;
	resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
	dataFormRef.value.resetFields();
	dataFormRef.value.clearValidate();

	formData.id = undefined;
}

/**
 * 删除天猫账单
 */
function handleDelete(id?: number) {
	const dictTypeIds = [id || ids.value].join(",");
	if (!dictTypeIds) {
		ElMessage.warning("请勾选删除项");
		return;
	}

	ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning",
	}).then(() => {
		deleteSysTmBill(dictTypeIds).then(() => {
			ElMessage.success("删除成功");
			resetQuery();
		});
	});
}

/** 打开导入弹窗 */
async function openImportDialog() {
	getGroupStore()
	importDialog.visible = true;
}

/**
 * Excel文件change事件
 *
 * @param file
 */
function handleExcelChange(file: UploadFile) {
	if (file.size !== undefined) {
		if (file.size > 20*1024*1024) {
			ElMessage.warning("上传文件大小已经超过20M，请尝试拆分成多个文件再上传");
			return false
		}
	}
	if (!/\.(csv|xlsx|xls|XLSX|XLS|CSV)$/.test(file.name)) {
		ElMessage.warning("上传Excel只能为xlsx、xls、csv格式");
		excelFile.value = undefined;
		excelFilelist.value = [];
		return false;
	}
	excelFile.value = file.raw;
}

/** 导入提交 */
function handleImport() {
	if (!excelFile.value) {
		ElMessage.warning("上传Excel文件不能为空");
		return false;
	}
	importRef.value.validate((isValid: boolean) => {
	  if (isValid) {
			const importLoading = ElLoading.service({
				lock: true,
				text: '导入中...',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			importSysTmBill(importParams.storeCode, excelFile.value).then((response) => {

				closeImportDialog();
				ElMessage.success('导入成功');
				resetQuery();
			}).finally(() => importLoading.close());
	  }
  })
}

/**  关闭导入弹窗 */
function closeImportDialog() {
	importDialog.visible = false;
	excelFile.value = undefined;
	excelFilelist.value = [];
}

/** 导出天猫账单 */
function handleExport() {
	const strIds = [ids.value].join(",");
	exportSysTmBill(strIds).then((response: any) => {
		const blob = new Blob([response.data], {
			type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
		});
		const a = document.createElement("a");
		const href = window.URL.createObjectURL(blob); // 下载的链接
		a.href = href;
		a.download = decodeURI(
			response.headers["content-disposition"].split(";")[1].split("=")[1]
		); // 获取后台设置的文件名称
		document.body.appendChild(a);
		a.click(); // 点击导出
		document.body.removeChild(a); // 下载完成移除元素
		window.URL.revokeObjectURL(href); // 释放掉blob对象
	});
}

/**
 * 获取所有店铺
 */
function getAllStore() {
	listAll().then((response) => {
		storeList.value = response.data;
	});
}

function getGroupStore() {
	listAll().then((response) => {
		storeGroup.value = []
		const group_store = lodash.groupBy(response.data, 'storeKeyName');
		for (let key in group_store) {
			storeGroup.value.push({'label': key, 'options': group_store[key]})
		}
	})
}

onMounted(() => {
	let now = new Date()
	let month = now.getMonth()
	let nowMonth;
	if (month < 9){
		nowMonth = now.getFullYear() + '0' + (now.getMonth() + 1) + ''
	}	else {
		nowMonth = now.getFullYear() + '' + (now.getMonth() + 1) + ''
	}
	monthList.value = [nowMonth, nowMonth]
	handleQuery();
	getAllStore()
});
</script>

<template>
	<div class="app-container">
		<div class="search-container">
			<el-form ref="queryFormRef" :model="queryParams" :inline="true">
				<el-form-item label="账单月份">
					<el-date-picker
							style="width: 200px"
							v-model="monthList"
							type="monthrange"
							range-separator="至"
							start-placeholder="开始月份"
							end-placeholder="结束月份"
							value-format="YYYYMM"
							:clearable="false"
					/>
				</el-form-item>
				<el-form-item label="主订单编号" prop="sourcePreformMainNo">
					<el-input
							v-model="queryParams.sourcePreformMainNo"
							placeholder="请输入主订单编号"
							clearable
							style="width: 180px"
							@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="店铺名称" prop="storeId">
					<el-select
							v-model="queryParams.storeId"
							placeholder="全部"
							clearable
							class="yz-el-select"
					>
						<el-option
								v-for="item in storeList"
								:key="item.commercePlatformStoreCode"
								:label="item.commercePlatformStoreName"
								:value="item.commercePlatformStoreCode"
						/>
					</el-select>
				</el-form-item>
				<el-form-item label="订单编号" prop="orderNo">
					<el-input
							v-model="queryParams.orderNo"
							placeholder="请输入订单编号"
							clearable
							style="width: 180px"
							@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="主订单编号" prop="mainOrderNo">
					<el-input
							v-model="queryParams.mainOrderNo"
							placeholder="请输入主订单编号"
							clearable
							style="width: 180px"
							@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item label="支付单号" prop="payNo">
					<el-input
							v-model="queryParams.payNo"
							placeholder="请输入支付单号"
							clearable
							style="width: 180px"
							@keyup.enter="handleQuery"
					/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery()"
					><i-ep-search />搜索</el-button
					>
					<el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
				</el-form-item>
			</el-form>
		</div>

		<el-card shadow="never">
			<template #header>
				<div class="flex justify-between">
					<div>
						<el-button
								v-hasPerm="['sys:tmBill:save']"
								type="success"
								@click="openDialog()"
						><i-ep-plus />新增</el-button
						>
						<el-button
								type="danger"
								:disabled="ids.length === 0"
								@click="handleDelete()"
								v-hasPerm="['sys:tmBill:delete']"
						><i-ep-delete />删除</el-button
						>
					</div>
					<div>
						<el-button class="ml-3" @click="openImportDialog" v-hasPerm="['sys:tmBill:import']"
						><template #icon><i-ep-top /></template>导入</el-button
						>
						<el-button class="ml-3" @click="handleExport" v-hasPerm="['sys:tmBill:export']"
						><template #icon><i-ep-download /></template>导出</el-button
						>
					</div>
				</div>
			</template>
			<el-table
					size="small"
					:header-row-style="{color: 'dimgray'}"
					v-loading="loading"
					highlight-current-row
					:data="sysTmBillList"
					border
					@selection-change="handleSelectionChange"
					:height="sysTmBillList && sysTmBillList.length > 0 ? 520 : 180"
			>
				<el-table-column type="selection" width="40" align="center" show-overflow-tooltip />
				<el-table-column label="店铺" prop="storeName" width="100" show-overflow-tooltip/>
				<el-table-column label="订单编号" prop="orderNo" width="100" show-overflow-tooltip/>
				<el-table-column label="支付单号" prop="payNo" width="100" show-overflow-tooltip/>
		  	<el-table-column label="支付详情" prop="payDetail" width="100" show-overflow-tooltip/>
		  	<el-table-column label="买家应付货款" prop="buyerPayableAmount" width="100" show-overflow-tooltip/>
		  	<el-table-column label="买家应付邮费" prop="buyerPayablePostage" width="100" show-overflow-tooltip/>
		  	<el-table-column label="买家支付积分" prop="buyerPoints" width="100" show-overflow-tooltip/>
		  	<el-table-column label="总金额" prop="buyerPayableTotalAmount" width="100" show-overflow-tooltip/>
		  <el-table-column label="返点积分" prop="returnPoints" width="100" show-overflow-tooltip/>
		  <el-table-column label="买家实际支付金额" prop="buyerPayableActAmount" width="100" show-overflow-tooltip/>
		  <el-table-column label="买家实际支付积分" prop="buyerActPoints" width="100" show-overflow-tooltip/>
		  <el-table-column label="订单状态" prop="orderStatus" width="100" show-overflow-tooltip/>
		  <el-table-column label="买家留言" prop="buyerRemark" width="100" show-overflow-tooltip/>
		  <el-table-column label="运送方式" prop="transportType" width="100" show-overflow-tooltip/>
		  <el-table-column label="订单创建时间" prop="orderCreateTime" width="140" show-overflow-tooltip/>
		  <el-table-column label="订单付款时间" prop="orderPayTime" width="140" show-overflow-tooltip/>
		  <el-table-column label="宝贝标题" prop="productTitle" width="100" show-overflow-tooltip/>
		  <el-table-column label="宝贝种类" prop="productType" width="100" show-overflow-tooltip/>
		  <el-table-column label="物流单号" prop="transportNo" width="100" show-overflow-tooltip/>
		  <el-table-column label="物流公司" prop="transportCompany" width="100" show-overflow-tooltip/>
		  <el-table-column label="备注标签" prop="remarkLabel" width="100" show-overflow-tooltip/>
		  <el-table-column label="商家备注" prop="sellerRemark" width="100" show-overflow-tooltip/>
		  <el-table-column label="宝贝总数量" prop="productQty" width="100" show-overflow-tooltip/>
		  <el-table-column label="店铺Id" prop="tmStoreId" width="100" show-overflow-tooltip/>
		  <el-table-column label="店铺名称" prop="tmStoreName" width="100" show-overflow-tooltip/>
			<el-table-column label="订单关闭原因" prop="cancelReason" width="100" show-overflow-tooltip/>
			<el-table-column label="卖家服务费" prop="sellerServiceAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="买家服务费" prop="buyerServiceAmount" width="100" show-overflow-tooltip/>
		  <el-table-column label="发票抬头" prop="invoiceTitle" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否手机订单" prop="phoneBill" width="100" show-overflow-tooltip/>
		  <el-table-column label="分阶段订单信息" prop="phasedOrderInfo" width="100" show-overflow-tooltip/>
		  <el-table-column label="特权订金订单id" prop="depositOrderId" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否上传合同照片" prop="uploadContract" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否上传小票" prop="uploadReceipts" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否代付" prop="otherPay" width="100" show-overflow-tooltip/>
		  <el-table-column label="定金排名" prop="depositRanking" width="100" show-overflow-tooltip/>
		  <el-table-column label="修改后的sku" prop="modifySku" width="100" show-overflow-tooltip/>
		  <el-table-column label="异常信息" prop="exceptionMessage" width="100" show-overflow-tooltip/>
			<el-table-column label="天猫卡券抵扣" prop="cardDeduction" width="100" show-overflow-tooltip/>
			<el-table-column label="集分宝抵扣" prop="jfbDeduction" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否是O2O交易" prop="oto" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售交易类型" prop="newTradeType" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售导购门店名称" prop="newTradeStoreName" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售导购门店id" prop="newTradeSellerId" width="100" show-overflow-tooltip/>
			<el-table-column label="购物金充值本金" prop="purchaseRechargeAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="购物金充值权益金" prop="purchaseRechargeQyAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="购物金消费本金" prop="purchaseConsumeAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="购物金消费权益金" prop="purchaseConsumeQyAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="退款金额" prop="refundAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="预约门店" prop="bookStore" width="100" show-overflow-tooltip/>
			<el-table-column label="确认收货时间" prop="confirmReceiveTime" width="140" show-overflow-tooltip/>
			<el-table-column label="打款商家金额" prop="payoutsAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="含应开票给个人的个人红包" prop="personalRedPackets" width="100" show-overflow-tooltip/>
		  <el-table-column label="是否信用购" prop="creditCard" width="100" show-overflow-tooltip/>
		  <el-table-column label="体验期结束时间" prop="trialEndTime" width="100" show-overflow-tooltip/>
			<el-table-column label="前N有礼" prop="nGift" width="100" show-overflow-tooltip/>
		  <el-table-column label="配送类型" prop="distributionType" width="100" show-overflow-tooltip/>
		  <el-table-column label="直播返现状态" prop="broadcastReturnStatus" width="100" show-overflow-tooltip/>
			<el-table-column label="返现金额" prop="cashbackAmount" width="100" show-overflow-tooltip/>
			<el-table-column label="是否赔付" prop="claims" width="100" show-overflow-tooltip/>
			<el-table-column label="延迟发货主动赔付金额" prop="delaySendIndemnityAmount" width="100" show-overflow-tooltip/>
		  <el-table-column label="赔付出账时间" prop="claimsTime" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售成交门店昵称" prop="newTradeDealStore" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售成交门店id" prop="newTradeDealStoreId" width="100" show-overflow-tooltip/>
		  <el-table-column label="新零售成交经销商id" prop="newTradeDealer" width="100" show-overflow-tooltip/>
		  <el-table-column label="预售订单" prop="preSaleOrder" width="100" show-overflow-tooltip/>
			<el-table-column label="发货时间" prop="sendTime" width="140" show-overflow-tooltip/>
			<el-table-column label="预售订单商家备注" prop="preSaleSellerRemark" width="100" show-overflow-tooltip/>
			<el-table-column label="主订单编号" prop="tmMainOrderNo" width="100" show-overflow-tooltip/>
			<el-table-column label="补差订单" prop="bcOrder" width="100" show-overflow-tooltip/>
			<el-table-column label="淘特订单" prop="ttOrder" width="100" show-overflow-tooltip/>
		  <el-table-column label="订单类型" prop="orderStatus" width="100" show-overflow-tooltip/>
		  <el-table-column label="预售下沉结果" prop="preSaleResult" width="100" show-overflow-tooltip/>
		  <el-table-column label="hold状态" prop="hoverStatus" width="100" show-overflow-tooltip/>
			<el-table-column label="应发货时间" prop="shouldSendTime" width="140" show-overflow-tooltip/>
			</el-table>

			<pagination
					v-if="total > 0"
					v-model:total="total"
					v-model:page="queryParams.pageNum"
					v-model:limit="queryParams.pageSize"
					@pagination="handleQuery"
			/>
		</el-card>

		<el-dialog
				v-model="dialog.visible"
				:title="dialog.title"
				width="500px"
				:close-on-click-modal="false"
				@close="closeDialog"
		>
			<el-form
					ref="dataFormRef"
					:model="formData"
					:rules="rules"
					label-width="150px"
			>
				<el-form-item label="店铺ID" prop="storeId">
					<el-input v-model="formData.storeId" placeholder="请输入店铺ID" clearable/>
				</el-form-item>
				<el-form-item label="订单编号" prop="orderNo">
					<el-input v-model="formData.orderNo" placeholder="请输入订单编号" clearable/>
				</el-form-item>
				<el-form-item label="主订单编号" prop="mainOrderNo">
					<el-input v-model="formData.mainOrderNo" placeholder="请输入主订单编号" clearable/>
				</el-form-item>
				<el-form-item label="补差订单" prop="bcOrder">
					<el-input v-model="formData.bcOrder" placeholder="请输入补差订单" clearable/>
				</el-form-item>
				<el-form-item label="淘特订单" prop="ttOrder">
					<el-input v-model="formData.ttOrder" placeholder="请输入淘特订单" clearable/>
				</el-form-item>
				<el-form-item label="支付单号" prop="payNo">
					<el-input v-model="formData.payNo" placeholder="请输入支付单号" clearable/>
				</el-form-item>
				<el-form-item label="订单状态" prop="orderStatus">
					<el-input v-model="formData.orderStatus" placeholder="请输入订单状态" clearable/>
				</el-form-item>
				<el-form-item label="订单类型" prop="orderType">
					<el-input v-model="formData.orderType" placeholder="请输入订单类型" clearable/>
				</el-form-item>
				<el-form-item label="订单关闭原因" prop="cancelReason">
					<el-input v-model="formData.cancelReason" placeholder="请输入订单关闭原因" clearable/>
				</el-form-item>
				<el-form-item label="订单创建时间" prop="orderCreateTime">
					<el-input v-model="formData.orderCreateTime" placeholder="请输入订单创建时间" clearable/>
				</el-form-item>
				<el-form-item label="订单付款时间" prop="orderPayTime">
					<el-input v-model="formData.orderPayTime" placeholder="请输入订单付款时间" clearable/>
				</el-form-item>
				<el-form-item label="发货时间" prop="sendTime">
					<el-input v-model="formData.sendTime" placeholder="请输入发货时间" clearable/>
				</el-form-item>
				<el-form-item label="确认收货时间" prop="confirmSendTime">
					<el-input v-model="formData.confirmSendTime" placeholder="请输入确认收货时间" clearable/>
				</el-form-item>
				<el-form-item label="应发货时间" prop="shouldSendTime">
					<el-input v-model="formData.shouldSendTime" placeholder="请输入应发货时间" clearable/>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleSubmit">确 定</el-button>
					<el-button @click="closeDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>

		<!-- 导入弹窗 -->
		<el-dialog
				v-model="importDialog.visible"
				:title="importDialog.title"
				width="600px"
				append-to-body
				@close="closeImportDialog"
		>
			<el-form label-width="80px" :model="importParams" :rules="importRules" ref="importRef">
				<el-form-item label="店铺" prop="storeCode">
					<el-select class="yz-el-select" v-model="importParams.storeCode" filterable placeholder="请选择店铺" style="width: 200px">
						<el-option-group
								v-for="group in storeGroup"
								:key="group.label"
								:label="group.label"
						>
							<el-option
									v-for="item in group.options"
									:key="item.id"
									:label="item.commercePlatformStoreName"
									:value="item.commercePlatformStoreCode"
							/>
						</el-option-group>
					</el-select>
				</el-form-item>
				<el-form-item label="Excel">
					<el-upload
							class="upload-demo"
							action=""
							drag
							:auto-upload="false"
							accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
							:file-list="excelFilelist"
							:on-change="handleExcelChange"
							:limit="1"
					>
						<el-icon class="el-icon--upload">
							<i-ep-upload-filled/>
						</el-icon>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<template #tip>
							<div class="el-upload__tip">xls/xlsx files</div>
						</template>
					</el-upload>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="handleImport">确 定</el-button>
					<el-button @click="closeImportDialog">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
